package org.llc.bpmn.service;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.llc.bpmn.model.qo.PageQo;
import org.llc.bpmn.model.vo.PageVo;
import org.llc.bpmn.model.vo.Process;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class BpmTemplateService {

    @Autowired
    ProcessEngine processEngine;

    @Autowired
    RepositoryService repositoryService;

    @SneakyThrows
    public void createBpmTemplate(MultipartFile file){

        InputStream inputStream = file.getInputStream();

        Deployment deployment = processEngine.getRepositoryService()
                .createDeployment()
                .name("流程定义")
                .addInputStream(file.getOriginalFilename(), inputStream)
                .deploy();
        log.info("流程模板部署成功, {}", file.getOriginalFilename());

    }

    public PageVo list(PageQo pageQo){
        int start = (pageQo.getPageNum() - 1) * pageQo.getPageSize();
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().listPage(start, pageQo.getPageSize());
        int total = repositoryService.createProcessDefinitionQuery().list().size();
        List<Process> result = new ArrayList<>();
        list.forEach(d->{
            Process p = new Process();
            p.setDeploymentId(d.getDeploymentId());
            p.setId(d.getId());
            p.setKey(d.getKey());
            p.setName(d.getName());
            p.setResourceName(d.getResourceName());
            p.setDiagramresourcename(d.getDiagramResourceName());
            result.add(p);
        });

        PageVo<Process> pageVo = new PageVo<>();
        pageVo.setRowCount(pageQo.getPageNum());
        pageVo.setCurrent(pageQo.getPageSize());
        pageVo.setRows(result);
        pageVo.setTotal(total);
        return pageVo;
    }



}
